import { DataTypes, Model, type Optional } from 'sequelize'
import sequelize from '../config'

// 点赞属性接口
export interface LikeAttributes {
  id: number
  userId: number
  targetType: 'post' | 'comment' // 点赞目标类型
  targetId: number // 目标ID（帖子ID或评论ID）
  createdAt?: Date
  updatedAt?: Date
}

// 创建点赞时的可选属性
export type LikeCreationAttributes = Optional<LikeAttributes, 'id' | 'createdAt' | 'updatedAt'>

// 点赞模型类
export class Like extends Model<LikeAttributes, LikeCreationAttributes> implements LikeAttributes {
  declare id: number
  declare userId: number
  declare targetType: 'post' | 'comment'
  declare targetId: number
  declare readonly createdAt: Date
  declare readonly updatedAt: Date
}

// 定义点赞模型
Like.init(
  {
    id: {
      type: DataTypes.INTEGER,
      autoIncrement: true,
      primaryKey: true
    },
    userId: {
      type: DataTypes.INTEGER,
      allowNull: false,
      comment: '点赞用户ID'
    },
    targetType: {
      type: DataTypes.ENUM('post', 'comment'),
      allowNull: false,
      comment: '点赞目标类型'
    },
    targetId: {
      type: DataTypes.INTEGER,
      allowNull: false,
      comment: '目标ID'
    }
  },
  {
    sequelize,
    tableName: 'likes',
    timestamps: true,
    indexes: [
      {
        fields: ['userId']
      },
      {
        fields: ['targetType', 'targetId']
      },
      {
        unique: true,
        fields: ['userId', 'targetType', 'targetId'],
        name: 'unique_user_target_like'
      }
    ]
  }
)

export default Like
